package com.xlh.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * Redis工具类
 *
 * @author cheer
 */
//@Configuration
public class RedisUtil implements DisposableBean {

    private static Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);

    // Redis服务器IP
    private static String ip;

    // Redis的端口号
    private static int port;

    // 可用连接实例的最大数目，默认值为8；
    // 如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
    private static int maxActive;

    // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
    private static int maxIdle;

    // 等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException；
    private static int maxWait;

    private static JedisPool jedisPool = null;

    // redis过期时间,以秒为单位
    // 一小时
    public final static int EXPR_HOUR = 60 * 60;
    // 一天
    public final static int EXPR_DAY = 60 * 60 * 24;
    // 一个月
    public final static int EXPR_MONTH = 60 * 60 * 24 * 30;

    /**
     * 同步获取Jedis实例
     *
     * @return Jedis
     */
    public static Jedis getJedis() {
        if (jedisPool == null) {
            synchronized (RedisUtil.class) {
                if (jedisPool == null) {
                    initialPool();
                }
            }
            if (jedisPool == null) {
                throw new NullPointerException("JedisPool is null.");
            }
        }
        return jedisPool.getResource();
    }

    /**
     * 初始化Redis连接池
     */
    private static void initialPool() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(maxActive);
            config.setMaxIdle(maxIdle);
            config.setMaxWaitMillis(maxWait);
            jedisPool = new JedisPool(config, ip, port);
        } catch (Exception e) {
            LOGGER.error("First create JedisPool error : " + e);
        }
    }

    /**
     * 设置 String
     *
     * @param key
     * @param value
     */
    public static void set(String key, String value) {
        try (Jedis jedis = getJedis()) {
            value = StringUtils.isBlank(value) ? "" : value;
            jedis.set(key, value);
        } catch (Exception e) {
            LOGGER.error("Set key error : " + e);
        }
    }

    /**
     * 设置 byte[]
     *
     * @param key
     * @param value
     */
    public static void set(byte[] key, byte[] value) {
        try (Jedis jedis = getJedis()) {
            jedis.set(key, value);
        } catch (Exception e) {
            LOGGER.error("Set key error : " + e);
        }
    }

    /**
     * 设置 String 过期时间
     *
     * @param key
     * @param value
     * @param seconds 以秒为单位
     */
    public static void set(String key, String value, int seconds) {
        try (Jedis jedis = getJedis()) {
            value = StringUtils.isBlank(value) ? "" : value;
            jedis.setex(key, seconds, value);
        } catch (Exception e) {
            LOGGER.error("Set keyex error : " + e);
        }
    }

    /**
     * 设置 byte[] 过期时间
     *
     * @param key
     * @param value
     * @param seconds 以秒为单位
     */
    public static void set(byte[] key, byte[] value, int seconds) {
        try (Jedis jedis = getJedis()) {
            jedis.setex(key, seconds, value);
        } catch (Exception e) {
            LOGGER.error("Set key error : " + e);
        }
    }

    /**
     * 获取String值
     *
     * @param key
     * @return value
     */
    public static String get(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.get(key);
        } catch (Exception e) {
            LOGGER.error("get key error : " + e);
        }
        return null;
    }

    /**
     * 获取byte[]值
     *
     * @param key
     * @return value
     */
    public static byte[] get(byte[] key) {
        try (Jedis jedis = getJedis()) {
            return jedis.get(key);
        } catch (Exception e) {
            LOGGER.error("get key error : " + e);
        }
        return null;
    }

    /**
     * 删除值
     *
     * @param key
     */
    public static void remove(String key) {
        try (Jedis jedis = getJedis()) {
            jedis.del(key);
        } catch (Exception e) {
            LOGGER.error("Remove keyex error : " + e);
        }
    }

    /**
     * 删除值
     *
     * @param key
     */
    public static void remove(byte[] key) {
        try (Jedis jedis = getJedis()) {
            jedis.del(key);
        } catch (Exception e) {
            LOGGER.error("Remove keyex error : " + e);
        }
    }

    /**
     * lpush
     *
     * @param key
     * @param key
     */
    public static void lpush(String key, String... strings) {
        try (Jedis jedis = getJedis()) {
            jedis.lpush(key, strings);
        } catch (Exception e) {
            LOGGER.error("lpush error : " + e);
        }
    }

    /**
     * lrem
     *
     * @param key
     * @param count
     * @param value
     */
    public static void lrem(String key, long count, String value) {
        try (Jedis jedis = getJedis()) {
            jedis.lrem(key, count, value);
        } catch (Exception e) {
            LOGGER.error("lpush error : " + e);
        }
    }

    /**
     * sadd
     *
     * @param key
     * @param value
     */
    public static void sadd(String key, String value) {
        try (Jedis jedis = getJedis()) {
            jedis.sadd(key, value);
        } catch (Exception e) {
            LOGGER.error("sadd error : " + e);
        }
    }

    /**
     * incr
     *
     * @param key
     * @return value
     */
    public static Long incr(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.incr(key);
        } catch (Exception e) {
            LOGGER.error("incr error : " + e);
        }
        return null;
    }

    /**
     * decr
     *
     * @param key
     * @return value
     */
    public static Long decr(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.decr(key);
        } catch (Exception e) {
            LOGGER.error("incr error : " + e);
        }
        return null;
    }

    @Override
    public void destroy() throws Exception {
        if (jedisPool != null) {
            jedisPool.close();
        }
    }

    @Value("${redis.ip}")
    public void setIp(String ip) {
        RedisUtil.ip = ip;
    }

    @Value("${redis.port}")
    public void setPort(int port) {
        RedisUtil.port = port;
    }

    @Value("${redis.max-active}")
    public void setMaxActive(int maxActive) {
        RedisUtil.maxActive = maxActive;
    }

    @Value("${redis.max-idle}")
    public void setMaxIdle(int maxIdle) {
        RedisUtil.maxIdle = maxIdle;
    }

    @Value("${redis.max-wait}")
    public void setMaxWait(int maxWait) {
        RedisUtil.maxWait = maxWait;
    }
}
